package chatroom;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * 聊天室服务器
 */
public class ChatroomServer {

    public static final int PORT = 8888;

    public static void main(String[] args) {
        //创建BossGroup
        EventLoopGroup bossGroup = new NioEventLoopGroup(2);
        //创建工作线程组
        EventLoopGroup workerGroup = new NioEventLoopGroup(10);
        try {
            //创建启动对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //设置线程组
            serverBootstrap.group(bossGroup,workerGroup)
                    //设置通道类型
                    .channel(NioServerSocketChannel.class)
                    //设置等待队列长度
                    .option(ChannelOption.SO_BACKLOG,100)
                    //设置初始化器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //设置处理器
                            socketChannel.pipeline().addLast(new StringDecoder()) //字符串解码器
                                    .addLast(new StringEncoder()) //字符串编码器
                                    .addLast(new ChatroomServerHandler()); //自定义处理器
                        }
                    });
            //绑定端口
            ChannelFuture channelFuture = serverBootstrap.bind(PORT).sync();
            //关闭通道
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

/**
 * 自定义聊天室服务器处理器
 */
class ChatroomServerHandler extends SimpleChannelInboundHandler<String> {

    //保存所有客户端通道的集合
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    //客户端连接成功
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+"上线了");
        //添加客户端通道到集合
        channels.add(ctx.channel());
        //广播消息
        channels.writeAndFlush(ctx.channel().remoteAddress()+"上线了");
    }

    //客户端断开
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+"下线了");
        //删除客户端通道
        channels.remove(ctx.channel());
        //广播消息
        channels.writeAndFlush(ctx.channel().remoteAddress()+"下线了");
    }

    //读客户端消息
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        //广播聊天消息
        channels.writeAndFlush(ctx.channel().remoteAddress()+"说："+s);
    }

    //异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
